<template>
  <Row>
    <Col span="24">
    <Card shadow>
      <p slot="title">
        <Icon type="md-qr-scanner" />
        区域轮廓数据
      </p>
      <Form
        ref="rangeForm"
        :model="formData"
        :rules="formRules"
        :label-width="90"
        label-position="left"
        class="form-wrapper"
      >
        <FormItem
          label="ID"
          prop="id"
        >
          <Row>
            <Col span="24">
            <Input
              v-model="formData.id"
              :disabled="useXlsKey.id || isInEdit"
              placeholder="请输入区域轮廓ID"
            ></Input>
            </Col>
          </Row>
          <Row v-if="useExcel">
            <Col span="24">
            <Checkbox v-model="useXlsKey.id">使用数据源的列名自动映射</Checkbox>
            </Col>
          </Row>
          <Row v-if="useXlsKey.id">
            <Col span="24">
            <Select
              v-model="xlsKey.id"
              @on-change="readFromXls('id')"
            >
              <Option
                v-for="item in xlsKeyList"
                :value="item.key"
                :key="item.id"
              >{{ item.key }}</Option>
            </Select>
            </Col>
          </Row>
        </FormItem>
        <FormItem
          label="围栏样式"
          prop="barrierStyle"
        >
          <Row>
            <Col span="24">
            <Select
              v-model="formData.barrierStyle"
              :disabled="useXlsKey.barrierStyle"
            >
              <Option
                v-for="item in barrierStyleDict"
                :value="item.value"
                :key="item.id"
              >{{ item.value }}</Option>
            </Select>
            </Col>
          </Row>
          <Row v-if="formData.barrierStyle">
            <Col span="24">
            <img
              :src="getBarrierStylePreview()"
              style="margin-top: 12px"
              class="preview"
            />
            </Col>
          </Row>
          <Row v-if="useExcel">
            <Col span="24">
            <Checkbox v-model="useXlsKey.barrierStyle">使用数据源的列名自动映射</Checkbox>
            </Col>
          </Row>
          <Row v-if="useXlsKey.barrierStyle">
            <Col span="24">
            <Select
              v-model="xlsKey.barrierStyle"
              @on-change="readFromXls('barrierStyle')"
            >
              <Option
                v-for="item in xlsKeyList"
                :value="item.key"
                :key="item.id"
              >{{ item.key }}</Option>
            </Select>
            </Col>
          </Row>
        </FormItem>
        <FormItem
          label="底部样式"
          prop="areaStyle"
        >
          <Row>
            <Col span="24">
            <Select
              v-model="formData.areaStyle"
              :disabled="useXlsKey.areaStyle"
            >
              <Option
                v-for="item in areaStyleDict"
                :value="item.value"
                :key="item.id"
              >{{ item.value }}</Option>
            </Select>
            </Col>
          </Row>
          <Row v-if="formData.areaStyle">
            <Col span="24">
            <img
              :src="getAreaStylePreview()"
              style="margin-top: 12px"
              class="preview"
            />
            </Col>
          </Row>
          <Row v-if="useExcel">
            <Col span="24">
            <Checkbox v-model="useXlsKey.areaStyle">使用数据源的列名自动映射</Checkbox>
            </Col>
          </Row>
          <Row v-if="useXlsKey.areaStyle">
            <Col span="24">
            <Select
              v-model="xlsKey.areaStyle"
              @on-change="readFromXls('areaStyle')"
            >
              <Option
                v-for="item in xlsKeyList"
                :value="item.key"
                :key="item.id"
              >{{ item.key }}</Option>
            </Select>
            </Col>
          </Row>
        </FormItem>
        <FormItem
          label="围栏高度"
          prop="height"
        >
          <Row>
            <Col span="24">
            <Input
              v-model="formData.height"
              :disabled="useXlsKey.height"
              placeholder="请输入围栏的高度，单位米"
            ></Input>
            </Col>
          </Row>
          <Row v-if="useExcel">
            <Col span="24">
            <Checkbox v-model="useXlsKey.height">使用数据源的列名自动映射</Checkbox>
            </Col>
          </Row>
          <Row v-if="useXlsKey.height">
            <Col span="24">
            <Select
              v-model="xlsKey.height"
              @on-change="readFromXls('height')"
            >
              <Option
                v-for="item in xlsKeyList"
                :value="item.key"
                :key="item.id"
              >{{ item.key }}</Option>
            </Select>
            </Col>
          </Row>
        </FormItem>
        <FormItem
          label="颜色"
          prop="color"
        >
          <Row>
            <Col span="24">
            <ColorPicker
              v-model="formData.color"
              :disabled="useXlsKey.color"
            ></ColorPicker>
            <span class="text" style="margin-left:12px;">{{formData.color}}</span>
            </Col>
          </Row>
          <Row v-if="useExcel">
            <Col span="24">
            <Checkbox v-model="useXlsKey.color">使用数据源的列名自动映射</Checkbox>
            </Col>
          </Row>
          <Row v-if="useXlsKey.color">
            <Col span="24">
            <Select
              v-model="xlsKey.color"
              @on-change="readFromXls('color')"
            >
              <Option
                v-for="item in xlsKeyList"
                :value="item.key"
                :key="item.id"
              >{{ item.key }}</Option>
            </Select>
            </Col>
          </Row>
        </FormItem>
        <FormItem
          label="绑定名称"
          prop="bindOn"
        >
          <Row>
            <Col span="24">
            <Input
              v-model="formData.bindOn"
              :disabled="useXlsKey.bindOn"
              placeholder="请输入路径的绑定名称"
            ></Input>
            </Col>
          </Row>
          <Row v-if="useExcel">
            <Col span="24">
            <Checkbox v-model="useXlsKey.bindOn">使用数据源的列名自动映射</Checkbox>
            </Col>
          </Row>
          <Row v-if="useXlsKey.bindOn">
            <Col span="24">
            <Select
              v-model="xlsKey.bindOn"
              @on-change="readFromXls('bindOn')"
            >
              <Option
                v-for="item in xlsKeyList"
                :value="item.key"
                :key="item.id"
              >{{ item.key }}</Option>
            </Select>
            </Col>
          </Row>
        </FormItem>
        <FormItem label="路径打点">
          <Row>
            <Col span="24">
            <Select
              v-model="joinedPOIList"
              multiple
              placeholder="选择要与之组合的POI"
              @on-change="composeFormPOIList"
            >
              <Option
                v-for="item in joinablePOIList"
                :value="item.id"
                :key="item.id"
              >{{item.title}}</Option>
            </Select>
            </Col>
          </Row>
        </FormItem>
        <FormItem>
          <Row>
            <Col span="12">
            <Button
              type="primary"
              @click="saveData"
            >保存数据</Button>
            </Col>
            <Col span="12">
            <Button
              type="error"
              v-if="isInEdit"
              @click="deleteData"
            >删除</Button>
            </Col>
          </Row>
        </FormItem>
      </Form>
    </Card>
    </Col>
  </Row>
</template>

<script>
import config from "@/config/global";
import { busEventEmit, busEventHandle } from "@/teleport/bus";
import { clone } from "@/libs/tools"

export default {
  name: "",
  props: {
    excelData: {
      type: Object,
      default: () => new Object(),
    },
  },
  data() {
    return {
      formData: {
        id: null,
        barrierStyle: null,
        areaStyle:null,
        height: null,
        color: "#000000",
        bindOn: null,
        points: [],
        poiList: [],
      },
      xlsKey: {
        id: null,
        barrierStyle: null,
        areaStyle:null,
        height: null,
        color: null,
        bindOn: null,
      },
      useXlsKey: {
        id: false,
        barrierStyle: false,
        areaStyle: false,
        height: false,
        color: false,
        bindOn: false,
      },
      joinedPOIList: [],
      joinablePOIList: [],
      xlsKeyList: [],
      barrierStyleDict: config.barrierStyleList.map((o) => {
        return { id: o, value: o };
      }),
      areaStyleDict: config.areaStyleList.map(o=>{
          return {id:o,value:o};
      }),
      barrierStylePreviewImages: {
        wave: require("@/assets/images/range-barrier-wave.webp"),
        loop_line: require("@/assets/images/range-barrier-loop_line.webp"),
        grid: require("@/assets/images/range-barrier-grid.webp"),
        stripe: require("@/assets/images/range-barrier-stripe.webp"),
        bias: require("@/assets/images/range-barrier-bias.webp"),
        box_wave_line: require("@/assets/images/range-barrier-box_wave_line.webp"),
        box_wave: require("@/assets/images/range-barrier-box_wave.webp"),
        box_solid_line: require("@/assets/images/range-barrier-box_solid_line.webp"),
        box_solid: require("@/assets/images/range-barrier-box_solid.webp")
      },
      areaStylePreviewImages:{
        none: require("@/assets/images/range-area-none.webp"),
        solid: require("@/assets/images/range-area-solid.webp"),
        block: require("@/assets/images/range-area-block.webp"),
        dot: require("@/assets/images/range-area-dot.webp"),
        dash_line: require("@/assets/images/range-area-dash_line.webp"),
        radar: require("@/assets/images/range-area-radar.webp")
      },
      formRules: {
        id: [{ required: true, message: "不能为空", trigger: "change" }],
        barrierStyle: [{ required: true, message: "不能为空", trigger: "change" }],
        areaStyle: [{ required: true, message: "不能为空", trigger: "change" }],
        height: [{ required: true, message: "不能为空", trigger: "change" }],
        color: [{ required: true, message: "不能为空", trigger: "change" }],
        bindOn: [{ required: true, message: "不能为空", trigger: "change" }],
      },
      isInEdit: false,
      useExcel: false,
    };
  },
  watch: {
    excelData: {
      handler(n, o) {
        if (n !== o) {
          if (store.useExcel) {
            this.useExcel = true;
            this.fillExcelDataKeyEnum(n);
            this.updateFromExcel();
          }
          if (n) {
            this.updatePathPoints(n.points);
          }
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    saveData() {
      this.$refs["rangeForm"].validate((valid) => {
        if (valid) {
          this.$Message.success("区域轮廓数据已保存");
          let resultData = {};
          //将Excel中除了渲染路径之外的其他字段进行保留，合并到要输出的JSON里
          if (store.useExcel) {
            let excelDataCopy = clone(this.excelData);
            for (let o in this.formData) {
              delete excelDataCopy[this.xlsKey[o]];
            }
            resultData = Object.assign(this.formData, excelDataCopy);
          } else {
            resultData = this.formData;
          }
          if (this.isInEdit) {
            //编辑模式下，保存后要推动AMAP更新样式
            busEventEmit("range-data-mutanted", clone(resultData));
            this.isInEdit = false;
          } else {
            //新建模式下，保存后要推动AMAP更新样式
            busEventEmit("range-data-complete", clone(resultData));
          }
        } else {
          this.$Message.error("请检查表单是否正确填写");
        }
      });
    },
    deleteData() {
      // TODO:
      busEventEmit("delete-range-result", this.formData.id);
      busEventEmit("delete-range", this.formData.id);
      this.isInEdit = false;
    },
    fillExcelDataKeyEnum(v) {
      let keys = Object.keys(v);
      this.xlsKeyList = keys.map((o, i) => {
        return { id: `${o}-${i}`, key: o };
      });
    },
    readFromXls(formKey) {
      let useXls = this.useXlsKey[formKey];
      let xlsKey = this.xlsKey[formKey];
      if (useXls) {
        this.formData[formKey] = this.excelData[xlsKey];
      }
    },
    updateFromExcel() {
      let formKeys = Object.keys(this.formData);
      formKeys.forEach((o, i) => {
        if (this.useXlsKey[o]) {
          this.readFromXls(o);
        }
      });
    },
    listenUpdateFormEvent() {
      const $this = this;
      busEventHandle("update-form-data", (msg) => {
        $this.updateFromEvent(msg);
      });
    },
    updateFromEvent(v) {
      this.formData = v;
      this.isInEdit = true;
      for (let index in this.useXlsKey) {
        this.useXlsKey[index] = false;
      }
    },
    updatePathPoints(points) {
      this.formData.points = points;
    },
    getBarrierStylePreview() {
      return this.barrierStylePreviewImages[this.formData.barrierStyle];
    },
    getAreaStylePreview() {
      return this.areaStylePreviewImages[this.formData.areaStyle];
    },
    loadJoinablePOI() {
      let createdMarker = store.drawHistory.filter((e) => {
        return e.CLASS_NAME === "AMap.Marker";
      });
      this.joinablePOIList = createdMarker.map((o) => {
        return o.getExtData();
      });
    },
    composeFormPOIList(list) {
      this.formData.poiList = list.map((o) => {
        return this.joinablePOIList.find((e) => {
          return o === e.id;
        });
      });
    },
  },
  created() {
    this.listenUpdateFormEvent();
    this.loadJoinablePOI();
  },
};
</script>

<style scoped>
.preview {
  width: 100%;
}
</style>